﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace QD.Utils
{
    public class StringUtils
    {
        public static string GetIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.UserHostAddress;

            if (string.IsNullOrEmpty(result) || !IsIP(result))
                return "127.0.0.1";

            return result;
        }

        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        public static string GetEmailHostName(string strEmail)
        {
            if (strEmail.IndexOf("@") < 0)
                return null;
            return strEmail.Substring(strEmail.LastIndexOf("@")).ToLower();
        }

        public static string RemoveHtml(string content)
        {
            if (string.IsNullOrEmpty(content))
                return string.Empty;
            return Regex.Replace(content, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
        }

        public static string RemoveUnsafeHtml(string content)
        {
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }



        public static string JsonCharFilter(string sourceStr)
        {
            sourceStr = sourceStr.Replace("\\", "\\\\");
            sourceStr = sourceStr.Replace("\b", "\\b");
            sourceStr = sourceStr.Replace("\t", "\\t");
            sourceStr = sourceStr.Replace("\n", "\\n");
            sourceStr = sourceStr.Replace("\v", "\\v");
            sourceStr = sourceStr.Replace("\f", "\\f");
            sourceStr = sourceStr.Replace("\r", "\\r");
            return sourceStr.Replace("\"", "\\\"");
        }

        public static string GetUnicodeSubString(string str, int len, string tailString)
        {
            if (string.IsNullOrEmpty(str))
                return null;

            string result = string.Empty;
            int byteLen = System.Text.Encoding.Default.GetByteCount(str);
            int charLen = str.Length;
            int byteCount = 0;
            int pos = 0;
            if (byteLen > len)
            {
                for (int i = 0; i < charLen; i++)
                {
                    if (Convert.ToInt32(str.ToCharArray()[i]) > 255)
                        byteCount += 2;
                    else
                        byteCount += 1;
                    if (byteCount > len)
                    {
                        pos = i;
                        break;
                    }
                    else if (byteCount == len)
                    {
                        pos = i + 1;
                        break;
                    }
                }

                if (pos >= 0)
                    result = str.Substring(0, pos) + tailString;
            }
            else
                result = str;

            return result;
        }

        public static bool ChkSql(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                string sql_1 = "exec|insert|delete|update|select|count|chr|mid|master|truncate|char|declare|proc|drop|create";
                string[] sql_c = sql_1.Split('|');
                foreach (string sl in sql_c)
                {
                    if (str.ToLower().IndexOf(sl) >= 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static string ChkSQL(string str)
        {
            return (str == null) ? "" : str.Replace("'", "''");
        }

        public static string[] GetHtmlImageUrlList(string sHtmlText)
        {
            if (!string.IsNullOrEmpty(sHtmlText))
            {

                Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*? [\s\t\r\n]*>", RegexOptions.IgnoreCase);


                MatchCollection matches = regImg.Matches(sHtmlText);

                int i = 0;
                string[] sUrlList = new string[matches.Count];


                foreach (Match match in matches)
                    sUrlList[i++] = match.Groups["imgUrl"].Value;
                return sUrlList;
            }
            return null;
        }

        public static string EncodeHtml(String text)
        {
            return System.Web.HttpUtility.HtmlDecode(text);
        }
        public static String DecodeHtml(String text)
        {
            return System.Web.HttpUtility.HtmlDecode(text);
        }

        public static String ArrayToString(Array arr, String splitChar = ",", String format = "{0}")
        {
            if (arr == null) return String.Empty;
            StringBuilder sb = new StringBuilder();
            foreach (object item in arr)
            {
                sb.AppendFormat(format, item, arr);
                sb.Append(splitChar);
            }
            if (!String.IsNullOrEmpty(splitChar))
                if (sb.Length > 0) sb.Remove(sb.Length - splitChar.Length, splitChar.Length);
            return sb.ToString();
        }

        
        public static string[] SplitString(string strContent, string strSplit)
        {
            if (!string.IsNullOrEmpty(strContent))
            {
                if (strContent.IndexOf(strSplit) < 0)
                    return new string[] { strContent };

                return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
            }
            else
                return new string[0] { };
        }

        
        public static string[] SplitString(string strContent, string strSplit, int count)
        {
            string[] result = new string[count];
            string[] splited = SplitString(strContent, strSplit);

            for (int i = 0; i < count; i++)
            {
                if (i < splited.Length)
                    result[i] = splited[i];
                else
                    result[i] = string.Empty;
            }

            return result;
        }

        public static bool StartsWithIgnoreCase(string target, string lookfor)
        {
            if (string.IsNullOrEmpty(target) || string.IsNullOrEmpty(lookfor))
            {
                return false;
            }

            if (lookfor.Length > target.Length)
            {
                return false;
            }
            return (0 == string.Compare(target, 0, lookfor, 0, lookfor.Length, StringComparison.OrdinalIgnoreCase));
        }
    }
}
